<script setup>
import {typeOptions} from "../../../utils/listData.js";
import {computed, nextTick, ref} from "vue";
import {getFuturesDetail} from "../../../utils/getData.js";
import {notify, getFuturesParams} from "../../../utils/commonScript.js";
import CEchartsStock from "../../../c-components/c-echarts-stock.vue";
import {GET, POST} from "../../../api/index.js";
import {useStore} from "vuex";
import CCard from "../../../c-components/c-card.vue";
import CText from "../../../c-components/c-text.vue";
import CLCandlestick from "../../../utils/CLCandlestick.js";
import EchartsOption from "../../../utils/EchartsOption.js";

const store = useStore()

const baseInfo = computed(() => {
  return store.state.baseInfo;
})

const typeValue = ref('30')
const stockCode = ref('FG')
const speed = ref(5)
const oldLines = ref([])
const kLines = ref([])
const echartsRef = ref(null)
const timer = ref(null)
const isStart = ref(false)
const isBuy = ref(false)
const currentLine = ref(null)
const initAmount = ref(200000)
const amount = ref(200000)
const stockNum = ref(0)
const tradeNum = ref(1)
const tradeList = ref([])
const n = 240 // 数据量
const buyType = ref(1)

const availablePurchase = computed(() => {
  return currentLine.value ? parseInt(parseInt(amount.value / currentLine.value.close) / 100) * 100 : 0
})

// 保存交易
const saveTrain = () => {
  console.log(JSON.stringify(oldLines.value))

  POST('/futures/train', {
    futuresCode: stockCode.value,
    initAmount: initAmount.value,
    endAmount: amount.value,
    level: typeValue.value,
    trainRecordDTOList: tradeList.value,
    lineData: JSON.stringify(oldLines.value),
    rise: amount.value -initAmount.value,
    ratio: ((amount.value -initAmount.value)/initAmount.value).toFixed(6)
  }).then(res => {
    store.dispatch('getUser')
  })

}

// 买入
const buyHandle = (type) => {
  if (currentLine.value) {
    const tradeAmount = tradeNum.value * currentLine.value.close
    if (tradeAmount > amount.value) {
      notify('可用金额不足', 'error')
    } else {
      amount.value -= tradeAmount
      stockNum.value += parseInt(tradeNum.value)

      if(type === 1) {
        notify('买开成功', 'success')
      } else {
        notify('卖开成功', 'success')
      }

      tradeList.value.push({
        tradeDate: currentLine.value.date,
        price: currentLine.value.close,
        num: parseInt(tradeNum.value),
        type: type,
        isClose: false
      })
      isBuy.value = true
      buyType.value = type
    }
  }
}

// 平仓
const closeHandle = () => {
  if (currentLine.value) {
    tradeList.value.forEach(item => {
      if(item.type !== 3 && !item.isClose) {

        const tradeAmount = tradeNum.value * currentLine.value.close

        if (tradeNum.value > stockNum.value) {
          notify('平仓数量不足', 'error')
        } else {
          if(item.type === 1) {
            amount.value += tradeAmount
          } else {
            amount.value += 2 * item.price - tradeAmount
          }
          stockNum.value -= parseInt(tradeNum.value)
          notify('平仓成功', 'success')

          tradeList.value.push({
            tradeDate: currentLine.value.date,
            price: currentLine.value.close,
            num: parseInt(tradeNum.value),
            type: 3,
            isClose: true
          })

          item.isClose = true
          isBuy.value = false
        }

      }
    })
    console.log(tradeList.value)
  }
}


// 开始模拟
const startHandle = () => {
  randomHandle(() => {
    if (isStart.value) {
      return
    }
    if (baseInfo.value.score <= 0) {
      return notify('积分不够！', 'error');
    }
    isStart.value = true
    tradeList.value = []
    tradeNum.value = 1
    amount.value = initAmount.value

    // 获取数据
    getFuturesDetail(getFuturesParams(stockCode.value, typeValue.value), (data) => {
      if (data && data.length > n) {
        let index = 120
        // 随机选择数据
        let offset = Math.floor(Math.random() * (data.length - n))
        oldLines.value = data.slice(offset, offset + n)
        kLines.value = oldLines.value.slice(0, index)

        currentLine.value = new CLCandlestick().klineToLines([kLines.value[kLines.value.length - 1]])[0]

        nextTick(() => {

          const echartsData = new CLCandlestick(kLines.value, {pageSize: 0, isJoinShow: false, isLineShow: true, isSegmentShow: true}).getData()
          const option = new EchartsOption(echartsData, {pageSize: 0, isJoinShow: false, isShowX: false}).getOption()

          echartsRef.value.setEchartsOption(option)

          timer.value = setInterval(() => {
            if (kLines.value.length >= oldLines.value.length) {
              clearInterval(timer.value)
              timer.value = null
              isStart.value = false
              // 训练结束全部平仓
              if (stockNum.value > 0) {
                tradeNum.value = stockNum.value
                closeHandle()
              }
              // 保存训练数据
              saveTrain()
            } else {
              kLines.value.push(oldLines.value[index])
              currentLine.value = new CLCandlestick().klineToLines([oldLines.value[index]])[0]

              const echartsData = new CLCandlestick(kLines.value, {pageSize: 0, isJoinShow: false, isLineShow: true, isSegmentShow: true}).getData()
              const option = new EchartsOption(echartsData, {pageSize: 0, isJoinShow: false, isShowX: false}).getOption()

              echartsRef.value.setEchartsOption(option)
              index++
            }
          }, speed.value * 1000)
        })
      } else {
        // 数据不足 重新自动选择
        isStart.value = false
        startHandle()
      }
    })
  })
}


// 随机选择品种
const randomHandle = (cb) => {
  const futuresList = sessionStorage.getItem('futuresList')
  if (futuresList) {
    let arr = JSON.parse(futuresList)
    stockCode.value = arr[Math.floor(Math.random() * arr.length)].code
    if (cb) {
      cb()
    }
  } else {
    GET("/futures/variety/list", {}).then(res => {
      let arr = res.data
      sessionStorage.setItem('futuresList', JSON.stringify(arr))
      stockCode.value = arr[Math.floor(Math.random() * arr.length)].code
      if (cb) {
        cb()
      }
    }).catch(() => {

    })
  }

}
</script>

<template>
  <div class="train">
    <c-card class="left">
      <div class="start" v-if="!isStart">
        <span @click="startHandle">开始训练</span>
      </div>
      <template  v-else>
        <c-echarts-stock ref="echartsRef" style="height:100%;"></c-echarts-stock>
      </template>
    </c-card>
    <c-card class="right">
      <el-form>
        <el-form-item label="级别">
          <el-select
              v-model="typeValue"
              placeholder="Select"
          >
            <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="频率">
          <el-input-number v-model="speed" :min="1"/>
        </el-form-item>
        <el-form-item label="初始">
          <c-text>{{initAmount}}</c-text>
        </el-form-item>
        <el-form-item label="可用">
          <c-text>{{amount}}</c-text>
        </el-form-item>
        <el-form-item label="持仓">
          <c-text>{{stockNum}}</c-text>
        </el-form-item>
        <el-form-item label="交易量">
          <el-input-number v-model="tradeNum" :min="1" :step="1" />
        </el-form-item>
        <el-form-item>
          <el-button :disabled="!isStart || isBuy" type="danger" @click="buyHandle(1)">买开</el-button>
          <el-button :disabled="!isStart || isBuy" type="success" @click="buyHandle(2)">卖开</el-button>
          <el-button :disabled="!isStart" type="primary" @click="closeHandle">平仓</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tradeList" stripe highlight-current-row height="350px">
        <el-table-column prop="tradeDate" label="时间"/>
        <el-table-column prop="type" label="类型">
          <template #default="{row}">
            <el-text v-if="row.type === 1" type="danger">买开</el-text>
            <el-text v-if="row.type === 2" type="success">卖开</el-text>
            <el-text v-if="row.type === 3" type="primary">平仓</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格"/>
      </el-table>
    </c-card>
  </div>
</template>

<style scoped lang="scss">
.train {
  display: flex;
  height: 100%;
  background: #f5f5f5;
  overflow: hidden;
  .left{
    flex: 1;
    margin-bottom: 0;
  }
  .right{
    width: 350px;
    margin-bottom: 0;
    margin-left: 10px;
  }
}
.start{
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  span{
    display: inline-block;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
    border-radius: 50%;
    background-color: #cb2020;
    color: #FFFFFF;
    cursor: pointer;
    font-size: 20px;
  }
}
</style>
